﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace BOSS.Framework.Search.Result
{
    /// <summary>
    /// 基于属性的结果条目类
    /// </summary>
    public class PropertyResultItem : AbstractResultItem
    {
        private static IDictionary<Type, IList<string>> typedFieldNames = new Dictionary<Type, IList<string>>();

        private IEnumerable<string> m_fieldNames;
        private object m_data;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="id"></param>
        /// <param name="score"></param>
        /// <param name="title"></param>
        /// <param name="data"></param>
        public PropertyResultItem(int id, float score, string title, object data)
            : base(id, score, title)
        {
            Type dataType = data.GetType();
            if (!typedFieldNames.ContainsKey(dataType))
            {
                lock (typedFieldNames)
                {
                    if (!typedFieldNames.ContainsKey(dataType))
                    {
                        IList<string> fieldNames = new List<string>();
                        foreach (PropertyInfo prop in dataType.GetProperties())
                        {
                            fieldNames.Add(prop.Name);
                        }
                        typedFieldNames.Add(dataType, fieldNames);
                        this.m_fieldNames = fieldNames;
                    }
                }
            }
            else
            {
                this.m_fieldNames = typedFieldNames[dataType];
            }
            this.m_data = data;
        }

        #region IResultItem Members

        /// <summary>
        /// 获取 条目的字段名称集合<br/>
        /// </summary>
        public override IEnumerable<string> FieldNames
        {
            get
            {
                return this.m_fieldNames;
            }
        }

        /// <summary>
        /// 获取 底层对象
        /// </summary>
        public override object UnderlayerObject
        {
            get
            {
                return this.m_data;
            }
        }

        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="fieldName"></param>
        /// <returns></returns>
        public override object GetValue(string fieldName)
        {
            try
            {
                return this.m_data.GetType().GetProperty(fieldName).GetValue(this.m_data, null);
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}
